/**
 * Map 
 * Define Map objects
 **/
var Map = function() {
	this.conf = null;
	this.cells = new Array();

	this.init = function(c) {
		log('*** INIT MAP ***');
		this.conf = c;

		var cellWidth = this.conf.cellSize.w;
		var cellHeight = this.conf.cellSize.h;
		var mapWidth = this.conf.mapSize.w;
		var mapHeight = this.conf.mapSize.h;

		for (var i = 0; i < mapWidth; i++) {
			this.cells[i] = new Array();
			for (var j = 0; j < mapHeight; j++) {
				this.cells[i][j] = new Cell();
				var b = {w : cellWidth, h : cellHeight};
				var p = {x : i, y : j};
				var object = this.conf.map[j][i];
				this.cells[i][j].init(b, p);

				if (object != 1) {
					switch (object) {
						case 2 : 	this.cells[i][j].addObject(new Ressource());
						break;

						case 3 : 	this.cells[i][j].addObject(new Building());
						break;

						default : 
					}
				}
			};
		};
	}

	this.clear = function() {
		var mapWidth = this.conf.mapSize.w;
		var mapHeight = this.conf.mapSize.h;
		for (var i = 0; i < mapWidth; i++) {
			for (var j = 0; j < mapHeight; j++) {
				this.cells[i][j].highlight = false;
			};
		};
	}

	this.update = function() {
		for (var i = 0; i < this.conf.mapSize.w; i++) {
			for (var j = 0; j < this.conf.mapSize.h; j++) {
				this.cells[i][j].update();
			};
		};
	}

	this.render = function() {
		for (var i = 0; i < this.conf.mapSize.w; i++) {
			for (var j = 0; j < this.conf.mapSize.h; j++) {
				this.cells[i][j].render();
			};
		};

		CTX.beginPath();
		CTX.rect(0, 0, this.getPixelWidth(), this.getPixelHeight());
		CTX.fillStyle = 'black';
		CTX.stroke();
		CTX.closePath();
	}

	// Access Configuration
	this.getConf = function() { return this.conf; }
	this.getCellWidth = function() { return this.conf.cellSize.w; }
	this.getCellHeight = function() { return this.conf.cellSize.h; }
	this.getPixelWidth = function() { return this.conf.mapSize.w * this.conf.cellSize.w; }
	this.getPixelHeight = function() { return this.conf.mapSize.h * this.conf.cellSize.h; }

	// Check Cell
	this.isWalkable = function(p) {
		return this.getCell(p).isWalkable();
	}

	// Get real position
	this.getPosition = function(p) {
		var realX = Math.floor(p.x / this.getCellWidth());
		var realY = Math.floor(p.y / this.getCellHeight());

		return {x:realX, y:realY}
	}

	// Get cell at a position
	this.getCell = function(p) {
		if (p.x >= 0 && p.x < this.conf.mapSize.w && p.y >= 0 && p.y < this.conf.mapSize.h) {
			if (this.cells[p.x][p.y] != undefined)
				return this.cells[p.x][p.y];
		}
	}
};
